<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>供应商列表</title>
    <link rel="stylesheet" href="../../../css/style.css">
    <!--    &lt;!&ndash; 引入JQuery JS 文件 &ndash;&gt;-->
    <!--    <script src="../../../assets/js/jquery-3.7.1.min.js"></script>-->
    <!--    &lt;!&ndash; 引入 Bootstrap CSS 文件 &ndash;&gt;-->
    <!--    <link rel="stylesheet" href="../../../assets/css/bootstrap.min.css">-->
    <!--    &lt;!&ndash; 引入 Bootstrap JS 文件 &ndash;&gt;-->
    <!--    <script src="../../../assets/js/bootstrap.bundle.min.js"></script>-->

    <!-- 引入 jQuery-->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <!-- 引入 Axios -->
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

    <style>
        /* 复制material_list.html的样式 */
        .submenu { display: none; }
        .menu-item.active > .submenu { display: block; }
        .menu-arrow { transition: transform 0.2s; }
        .menu-item.active > a > .menu-arrow { transform: rotate(90deg); }
        .table th { background-color: #f8f9fa; }
        .submenu li a.active { color: #28a745; font-weight: bold; transform: translateY(2px); display: inline-block; }
        .search-area { background: #f8f9fa; padding: 10px; border-radius: 8px; margin: 10px 0; width: 100%; }
        .search-row { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
        .search-item { flex: 0 0 auto; margin-right: 10px; margin-bottom: 5px; }
        .search-item .form-control, .search-item .form-select { width: 120px; height: 31px; font-size: 14px; }
        .search-item .btn { padding: 4px 8px; }
        .search-label { display: block; margin-bottom: 5px; font-size: 14px; color: #555; white-space: nowrap; }
        .table-responsive { overflow-x: auto; margin: 0 -20px; padding: 0 20px; }
        .custom-table { width: 100%; border-collapse: separate; border-spacing: 0; }
        .custom-table th { background: #f8f9fa; color: #495057; font-weight: 600; padding: 12px 15px; border-bottom: 2px solid #dee2e6; white-space: nowrap; }
        .custom-table td { padding: 12px 15px; border-bottom: 1px solid #eee; vertical-align: middle; }
        .action-buttons { display: flex; gap: 8px; }
        .action-buttons .btn {
            padding: 4px 10px;
            font-size: 13px;
            min-width: 60px;
            white-space: nowrap;
        }
        .page-title { font-size: 22px; font-weight: 600; margin-bottom: 20px; color: #333; display: flex; align-items: center; gap: 10px; }
        .page-title-icon { font-size: 24px; }
        .ms-auto { margin-left: auto; }
        .add-button { padding: 8px 16px; display: flex; align-items: center; gap: 5px; font-weight: 500; }
        .content-wrapper { padding: 20px; background: #fff; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); margin: 20px; }

        /* 表单验证样式 */
        .invalid-feedback {
            display: block;
            width: 100%;
            margin-top: 0.25rem;
            font-size: 0.875em;
            color: #dc3545;
        }
        .form-control.is-invalid, .form-select.is-invalid {
            border-color: #dc3545;
            padding-right: calc(1.5em + 0.75rem);
            background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12' width='12' height='12' fill='none' stroke='%23dc3545'%3e%3ccircle cx='6' cy='6' r='4.5'/%3e%3cpath stroke-linejoin='round' d='M5.8 3.6h.4L6 6.5z'/%3e%3ccircle cx='6' cy='8.2' r='.6' fill='%23dc3545' stroke='none'/%3e%3c/svg%3e");
            background-repeat: no-repeat;
            background-position: right calc(0.375em + 0.1875rem) center;
            background-size: calc(0.75em + 0.375rem) calc(0.75em + 0.375rem);
        }
        .form-select.is-invalid {
            background-position: right 0.75rem center, center right 2.25rem;
            background-size: 16px 12px, calc(0.75em + 0.375rem) calc(0.75em + 0.375rem);
        }
        .form-control.is-invalid:focus, .form-select.is-invalid:focus {
            border-color: #dc3545;
            box-shadow: 0 0 0 0.25rem rgba(220, 53, 69, 0.25);
        }
        /* iOS风格模态框样式 */
        .ios-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.4);
            backdrop-filter: blur(10px);
            -webkit-backdrop-filter: blur(10px);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 1050;
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .ios-modal.show {
            display: flex;
            opacity: 1;
        }

        .modal.ios-style .modal-dialog {
            max-width: 500px;
            margin: 0 auto;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 90%;
            max-width: 500px;
        }

        .modal.ios-style .modal-content {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(20px);
            -webkit-backdrop-filter: blur(20px);
            border-radius: 20px;
            border: none;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
            overflow: hidden;
        }

        .modal.ios-style .modal-header {
            padding: 20px 20px 10px;
            text-align: center;
            border-bottom: 1px solid rgba(0, 0, 0, 0.1);
            position: relative;
        }

        .modal.ios-style .modal-title {
            font-size: 18px;
            font-weight: 600;
            color: #333;
            width: 100%;
            text-align: center;
        }

        .modal.ios-style .btn-close {
            position: absolute;
            right: 20px;
            top: 50%;
            transform: translateY(-50%);
            background: none;
            opacity: 0.5;
            transition: opacity 0.2s;
        }

        .modal.ios-style .btn-close:hover {
            opacity: 1;
        }

        .modal.ios-style .modal-body {
            padding: 20px;
            max-height: 60vh;
            overflow-y: auto;
        }

        .modal.ios-style .form-label {
            font-weight: 500;
            color: #666;
            font-size: 14px;
            margin-bottom: 8px;
        }

        .modal.ios-style .form-control,
        .modal.ios-style .form-select {
            border-radius: 12px;
            border: 1px solid rgba(0, 0, 0, 0.1);
            padding: 10px 15px;
            font-size: 15px;
            transition: all 0.2s;
        }

        .modal.ios-style .form-control:focus,
        .modal.ios-style .form-select:focus {
            border-color: #007AFF;
            box-shadow: 0 0 0 3px rgba(0, 122, 255, 0.1);
        }

        .modal.ios-style .modal-footer {
            padding: 15px 20px 20px;
            border-top: 1px solid rgba(0, 0, 0, 0.1);
            justify-content: center;
            gap: 10px;
        }

        .modal.ios-style .btn {
            border-radius: 12px;
            padding: 10px 25px;
            font-size: 15px;
            font-weight: 500;
            transition: all 0.2s;
        }

        .modal.ios-style .btn-primary {
            background: #007AFF;
            border: none;
        }

        .modal.ios-style .btn-primary:hover {
            background: #0056CC;
        }

        .modal.ios-style .btn-secondary {
            background: #E5E5EA;
            border: none;
            color: #333;
        }

        .modal.ios-style .btn-secondary:hover {
            background: #D1D1D6;
        }

        /* 滚动条样式 */
        .modal.ios-style .modal-body::-webkit-scrollbar {
            width: 4px;
        }

        .modal.ios-style .modal-body::-webkit-scrollbar-track {
            background: transparent;
        }

        .modal.ios-style .modal-body::-webkit-scrollbar-thumb {
            background: rgba(0, 0, 0, 0.2);
            border-radius: 2px;
        }


        .ios-modal-content {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(20px);
            -webkit-backdrop-filter: blur(20px);
            border-radius: 20px;
            padding: 0;
            max-width: 400px;
            width: 90%;
            max-height: 80vh;
            overflow: hidden;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
            transform: scale(0.8);
            transition: transform 0.3s ease;
        }

        .ios-modal.show .ios-modal-content {
            transform: scale(1);
        }

        .ios-modal-header {
            padding: 20px 20px 10px;
            text-align: center;
            border-bottom: 1px solid rgba(0, 0, 0, 0.1);
        }

        .ios-modal-title {
            font-size: 18px;
            font-weight: 600;
            color: #333;
            margin: 0;
        }

        .ios-modal-body {
            padding: 20px;
            max-height: 60vh;
            overflow-y: auto;
        }

        .ios-detail-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 0;
            border-bottom: 1px solid rgba(0, 0, 0, 0.05);
        }

        .ios-detail-item:last-child {
            border-bottom: none;
        }

        .ios-detail-label {
            font-weight: 500;
            color: #666;
            font-size: 14px;
        }

        .ios-detail-value {
            font-weight: 400;
            color: #333;
            font-size: 14px;
            text-align: right;
            max-width: 60%;
            word-wrap: break-word;
        }

        .ios-modal-footer {
            padding: 15px 20px 20px;
            text-align: center;
        }

        .ios-close-btn {
            background: #007AFF;
            color: white;
            border: none;
            border-radius: 12px;
            padding: 12px 30px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: background 0.2s ease;
        }

        .ios-close-btn:hover {
            background: #0056CC;
        }

        .modal.ios-style .btn-secondary {
            background: #E5E5EA;
            border: none;
            color: #333;
        }

        .modal.ios-style .btn-secondary:hover {
            background: #D1D1D6;
        }

        /* 滚动条样式 */
        .ios-modal-body::-webkit-scrollbar {
            width: 4px;
        }

        .ios-modal-body::-webkit-scrollbar-track {
            background: transparent;
        }

        .ios-modal-body::-webkit-scrollbar-thumb {
            background: rgba(0, 0, 0, 0.2);
            border-radius: 2px;
        }


        /* 表单验证样式 */
        .invalid-feedback {
            display: block;
            width: 100%;
            margin-top: 0.25rem;
            font-size: 0.875em;
            color: #dc3545;
        }
        .form-control.is-invalid, .form-select.is-invalid {
            border-color: #dc3545;
            padding-right: calc(1.5em + 0.75rem);
            background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12' width='12' height='12' fill='none' stroke='%23dc3545'%3e%3ccircle cx='6' cy='6' r='4.5'/%3e%3cpath stroke-linejoin='round' d='M5.8 3.6h.4L6 6.5z'/%3e%3ccircle cx='6' cy='8.2' r='.6' fill='%23dc3545' stroke='none'/%3e%3c/svg%3e");
            background-repeat: no-repeat;
            background-position: right calc(0.375em + 0.1875rem) center;
            background-size: calc(0.75em + 0.375rem) calc(0.75em + 0.375rem);
        }
        .form-select.is-invalid {
            background-position: right 0.75rem center, center right 2.25rem;
            background-size: 16px 12px, calc(0.75em + 0.375rem) calc(0.75em + 0.375rem);
        }
        .form-control.is-invalid:focus, .form-select.is-invalid:focus {
            border-color: #dc3545;
            box-shadow: 0 0 0 0.25rem rgba(220, 53, 69, 0.25);
        }

        /* 添加按钮组样式 */
        .action-button-group {
            display: flex;
            gap: 15px;
            align-items: center;
            justify-content: flex-end;
        }
        
        .action-button-group .add-button {
            padding: 8px 16px;
            display: flex;
            align-items: center;
            gap: 8px;
            font-weight: 500;
            min-width: 140px;
            justify-content: center;
        }

        /* 调整模态框宽度 */
        .modal-xl-custom {
            max-width: 95%;
            width: 1400px;
        }

        .modal-lg-custom {
            max-width: 90%;
            width: 800px;
        }

        /* 调整表格单元格样式 */
        .records-table td {
            max-width: 300px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        .records-table td.description-cell {
            white-space: normal;
            line-height: 1.4;
            min-width: 250px;
        }

        /* 添加可点击行的样式 */
        .records-table tbody tr {
            cursor: pointer;
            transition: background-color 0.2s;
        }
        .records-table tbody tr:hover {
            background-color: rgba(0, 123, 255, 0.05);
        }

        /* 详情模态框中的信息项样式 */
        .detail-item {
            margin-bottom: 15px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
        }
        .detail-item:last-child {
            border-bottom: none;
        }
        .detail-label {
            font-weight: 600;
            color: #666;
            margin-bottom: 5px;
        }
        .detail-value {
            color: #333;
            line-height: 1.5;
        }

        /* 调整详情模态框中的信息布局 */
        .detail-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 20px;
        }

        .detail-grid .detail-item.full-width {
            grid-column: 1 / -1;
        }

        .detail-value.description {
            white-space: pre-wrap;
            background: #f8f9fa;
            padding: 15px;
            border-radius: 8px;
            font-size: 14px;
        }
    </style>
</head>
<body>
<div class="admin-layout">
    <!-- 顶部导航栏 -->
    <header class="admin-header">
        <div class="header-left">
            <div class="logo">生产过程管理系统</div>
        </div>
        <div class="header-right">
            <span class="user-info">员工</span>
            <span class="user-name">
                    <script>
                        try {
                            const userInfo = localStorage.getItem('userInfo');
                            const user = JSON.parse(userInfo);
                            document.write(user.name || '未登录');
                        } catch (e) {
                            document.write('未登录');
                        }
                    </script>
                </span>
            <button class="logout-btn" onclick="logout()">退出</button>
        </div>
    </header>
    <!-- 左侧菜单 -->
    <aside class="admin-sidebar">
        <ul class="menu-list">
            <li class="menu-item">
                <a href="../homepage/employee_home.html">
                    <span class="menu-icon">🏠</span>
                    <span class="menu-title">首页</span>
                </a>
            </li>
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <span class="menu-icon">📦</span>
                    <span class="menu-title">物料管理</span>
                    <span class="menu-arrow"></span>
                </a>
                <ul class="submenu">
                    <li><a href="../material/material_list.html">物料列表</a></li>
                </ul>
            </li>
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <span class="menu-icon">⚙️</span>
                    <span class="menu-title">设备管理</span>
                    <span class="menu-arrow"></span>
                </a>
                <ul class="submenu">
                    <li><a href="../device/device_list.html">设备列表</a></li>
                </ul>
            </li>
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <span class="menu-icon">📝</span>
                    <span class="menu-title">产品管理</span>
                    <span class="menu-arrow"></span>
                </a>
                <ul class="submenu">
                    <li><a href="../product/product_plan_list.html">查看生产计划</a></li>
                    <li><a href="../product/product_plan_commit.html">提交完成情况</a></li>
                </ul>
            </li>
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <span class="menu-icon">🏢</span>
                    <span class="menu-title">供应商管理</span>
                    <span class="menu-arrow"></span>
                </a>
                <ul class="submenu active">
                    <li><a href="provider_list.html" class="active">供应商列表</a></li>
                </ul>
            </li>
        </ul>
    </aside>
    <!-- 主内容区域 -->
    <main class="admin-main">
        <div class="content-wrapper">
            <div class="page-title">
                <span class="page-title-icon">🏢</span>
                <span>供应商列表</span>
                <div class="ms-auto action-button-group">
                    <button class="btn btn-info add-button" onclick="showApplicationRecords()">
                        <i class="fas fa-list"></i> 我的申请记录
                    </button>
                    <button class="btn btn-warning add-button" onclick="showComplaintRecords()">
                        <i class="fas fa-exclamation-circle"></i> 我的投诉记录
                    </button>
                    <button class="btn btn-success add-button" onclick="showProviderApplicationForm()">
                        <i class="fas fa-plus"></i> 供应商申请准入
                    </button>
                </div>
            </div>
            <!-- 搜索区域 -->
            <div class="search-area">
                <div class="search-row">
                    <div class="search-item">
                        <label class="search-label">供应商名称</label>
                        <input type="text" class="form-control form-control-sm" id="searchProviderName" placeholder="请输入名称">
                    </div>
                    <div class="search-item">
                        <label class="search-label">企业类型</label>
                        <select class="form-select form-select-sm" id="searchCompanyType">
                            <option value="">全部</option>
                            <option value="国有企业">国有企业</option>
                            <option value="民营企业">民营企业</option>
                            <option value="外资企业">外资企业</option>
                        </select>
                    </div>
                    <div class="search-item">
                        <label class="search-label">经理姓名</label>
                        <input type="text" class="form-control form-control-sm" id="searchManagerName" placeholder="请输入姓名">
                    </div>
                    <div class="search-item">
                        <label class="search-label">供应商评级</label>
                        <select class="form-select form-select-sm" id="searchProviderRating">
                            <option value="">全部</option>
                            <option value="1">1星</option>
                            <option value="2">2星</option>
                            <option value="3">3星</option>
                            <option value="4">4星</option>
                            <option value="5">5星</option>
                        </select>
                    </div>
                    <div class="search-item">
                        <button class="btn btn-sm btn-outline-primary" onclick="searchProviders()">🔍</button>
                    </div>
                    <div class="search-item">
                        <button class="btn btn-sm btn-outline-secondary" onclick="resetSearch()">↺</button>
                    </div>
                </div>
            </div>
            <!-- 数据表格 -->
            <div class="table-responsive">
                <table class="table table-hover table-striped custom-table mb-0">
                    <thead>
                    <tr>
                        <th>供应商名称</th>
                        <th>厂址</th>
                        <th>经理姓名</th>
                        <th>经理电话</th>
                        <th>企业类型</th>
                        <th>注册资本</th>
                        <th>员工数量</th>
                        <th>成立年份</th>
                        <th>供应商评级</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody id="providerTableBody">
                    <!-- 数据将通过JavaScript动态加载 -->
                    </tbody>
                </table>
            </div>
        </div>
    </main>
</div>

<!-- 供应商投诉模态框 -->
<div class="modal fade ios-style" id="providerComplaintModal" tabindex="-1" aria-labelledby="providerComplaintModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="providerComplaintModalLabel">供应商投诉</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="providerComplaintForm">
                    <div class="mb-3">
                        <label for="complaintProviderName" class="form-label">供应商名称</label>
                        <input type="text" class="form-control" id="complaintProviderName" readonly>
                    </div>
                    <div class="mb-3">
                        <label for="defectiveMaterial" class="form-label">问题材料 <span class="text-danger">*</span></label>
                        <select class="form-select" id="defectiveMaterial" required>
                            <option value="" selected disabled>请选择问题材料</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="complaintDescription" class="form-label">投诉描述 <span class="text-danger">*</span></label>
                        <textarea class="form-control" id="complaintDescription" rows="4" required></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="submitComplaint()">提交投诉</button>
            </div>
        </div>
    </div>
</div>

<!-- 供应商申请准入模态框 -->
<div class="modal fade ios-style" id="providerApplicationModal" tabindex="-1" aria-labelledby="providerApplicationModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="providerApplicationModalLabel">供应商申请准入</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="providerApplicationForm">
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="providerName" class="form-label">供应商名称 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="providerName" required>
                        </div>
                        <div class="col-md-6">
                            <label for="factoryAddress" class="form-label">厂址 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="factoryAddress" required>
                        </div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="managerName" class="form-label">经理姓名 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="managerName" required>
                        </div>
                        <div class="col-md-6">
                            <label for="managerPhone" class="form-label">经理电话 <span class="text-danger">*</span></label>
                            <input type="tel" class="form-control" id="managerPhone" required>
                        </div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="companyType" class="form-label">企业类型 <span class="text-danger">*</span></label>
                            <select class="form-select" id="companyType" required>
                                <option value="" selected disabled>请选择企业类型</option>
                                <option value="国有企业">国有企业</option>
                                <option value="民营企业">民营企业</option>
                                <option value="外资企业">外资企业</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label for="registeredCapital" class="form-label">注册资本(万元) <span class="text-danger">*</span></label>
                            <input type="number" class="form-control" id="registeredCapital" min="0" step="0.01" required>
                        </div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="employeeCount" class="form-label">员工数量 <span class="text-danger">*</span></label>
                            <input type="number" class="form-control" id="employeeCount" min="1" required>
                        </div>
                        <div class="col-md-6">
                            <label for="establishedYear" class="form-label">成立年份 <span class="text-danger">*</span></label>
                            <input type="number" class="form-control" id="establishedYear" min="1900" max="2099" required>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="profile" class="form-label">企业简介</label>
                        <textarea class="form-control" id="profile" rows="3"></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="submitProviderApplication()">提交申请</button>
            </div>
        </div>
    </div>
</div>
<!-- iOS风格供应商详情模态框 -->
<div class="ios-modal" id="providerDetailModal">
    <div class="ios-modal-content">
        <div class="ios-modal-header">
            <h5 class="ios-modal-title">供应商详情</h5>
        </div>
        <div class="ios-modal-body">
            <div class="ios-detail-item">
                <span class="ios-detail-label">供应商名称</span>
                <span class="ios-detail-value" id="detailProviderName">-</span>
            </div>
            <div class="ios-detail-item">
                <span class="ios-detail-label">厂址</span>
                <span class="ios-detail-value" id="detailFactoryAddress">-</span>
            </div>
            <div class="ios-detail-item">
                <span class="ios-detail-label">经理姓名</span>
                <span class="ios-detail-value" id="detailManagerName">-</span>
            </div>
            <div class="ios-detail-item">
                <span class="ios-detail-label">经理电话</span>
                <span class="ios-detail-value" id="detailManagerPhone">-</span>
            </div>
            <div class="ios-detail-item">
                <span class="ios-detail-label">企业类型</span>
                <span class="ios-detail-value" id="detailCompanyType">-</span>
            </div>
            <div class="ios-detail-item">
                <span class="ios-detail-label">注册资本</span>
                <span class="ios-detail-value" id="detailRegisteredCapital">-</span>
            </div>
            <div class="ios-detail-item">
                <span class="ios-detail-label">员工数量</span>
                <span class="ios-detail-value" id="detailEmployeeCount">-</span>
            </div>
            <div class="ios-detail-item">
                <span class="ios-detail-label">成立年份</span>
                <span class="ios-detail-value" id="detailEstablishedYear">-</span>
            </div>
            <div class="ios-detail-item">
                <span class="ios-detail-label">供应商评级</span>
                <span class="ios-detail-value" id="detailProviderRating">-</span>
            </div>
            <div class="ios-detail-item">
                <span class="ios-detail-label">企业简介</span>
                <span class="ios-detail-value" id="detailProfile">-</span>
            </div>
        </div>
        <div class="ios-modal-footer">
            <button class="ios-close-btn" onclick="closeProviderDetailModal()">关闭</button>
        </div>
    </div>
</div>

<!-- 申请记录模态框 -->
<div class="modal fade ios-style" id="applicationRecordsModal" tabindex="-1" aria-labelledby="applicationRecordsModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl-custom">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="applicationRecordsModalLabel">供应商申请记录</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="table-responsive">
                    <table class="table table-hover records-table">
                        <thead>
                            <tr>
                                <th style="width: 20%">供应商名称</th>
                                <th style="width: 15%">企业类型</th>
                                <th style="width: 15%">经理姓名</th>
                                <th style="width: 20%">经理电话</th>
                                <th style="width: 10%">状态</th>
                            </tr>
                        </thead>
                        <tbody id="applicationRecordsBody">
                            <!-- 数据将通过JavaScript动态加载 -->
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<!-- 投诉记录模态框 -->
<div class="modal fade ios-style" id="complaintRecordsModal" tabindex="-1" aria-labelledby="complaintRecordsModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl-custom">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="complaintRecordsModalLabel">供应商投诉记录</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="table-responsive">
                    <table class="table table-hover records-table">
                        <thead>
                            <tr>
                                <th style="width: 20%">供应商名称</th>
                                <th style="width: 20%">问题材料</th>
                                <th style="width: 50%">投诉描述</th>
                                <th style="width: 10%">状态</th>
                            </tr>
                        </thead>
                        <tbody id="complaintRecordsBody">
                            <!-- 数据将通过JavaScript动态加载 -->
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<!-- 申请详情模态框 -->
<div class="modal fade ios-style" id="applicationDetailModal" tabindex="-1" aria-labelledby="applicationDetailModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg-custom">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="applicationDetailModalLabel">申请详情</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="detail-grid">
                    <div class="detail-item">
                        <div class="detail-label">供应商名称</div>
                        <div class="detail-value" id="appDetail-providerName">-</div>
                    </div>
                    <div class="detail-item">
                        <div class="detail-label">企业类型</div>
                        <div class="detail-value" id="appDetail-companyType">-</div>
                    </div>
                    <div class="detail-item">
                        <div class="detail-label">经理姓名</div>
                        <div class="detail-value" id="appDetail-managerName">-</div>
                    </div>
                    <div class="detail-item">
                        <div class="detail-label">经理电话</div>
                        <div class="detail-value" id="appDetail-managerPhone">-</div>
                    </div>
                    <div class="detail-item">
                        <div class="detail-label">注册资本</div>
                        <div class="detail-value" id="appDetail-registeredCapital">-</div>
                    </div>
                    <div class="detail-item">
                        <div class="detail-label">员工数量</div>
                        <div class="detail-value" id="appDetail-employeeCount">-</div>
                    </div>
                    <div class="detail-item">
                        <div class="detail-label">成立年份</div>
                        <div class="detail-value" id="appDetail-establishedYear">-</div>
                    </div>
                    <div class="detail-item">
                        <div class="detail-label">申请状态</div>
                        <div class="detail-value" id="appDetail-status">-</div>
                    </div>
                    <div class="detail-item full-width">
                        <div class="detail-label">企业简介</div>
                        <div class="detail-value description" id="appDetail-profile">-</div>
                    </div>
                    <div class="detail-item full-width" id="appDetail-reviewContainer" style="display: none;">
                        <div class="detail-label">审批意见</div>
                        <div class="detail-value description" id="appDetail-reviewDescription">-</div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<!-- 投诉详情模态框 -->
<div class="modal fade ios-style" id="complaintDetailModal" tabindex="-1" aria-labelledby="complaintDetailModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg-custom">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="complaintDetailModalLabel">投诉详情</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="detail-grid">
                    <div class="detail-item">
                        <div class="detail-label">供应商名称</div>
                        <div class="detail-value" id="compDetail-providerName">-</div>
                    </div>
                    <div class="detail-item">
                        <div class="detail-label">问题材料</div>
                        <div class="detail-value" id="compDetail-defectiveMaterial">-</div>
                    </div>
                    <div class="detail-item">
                        <div class="detail-label">投诉状态</div>
                        <div class="detail-value" id="compDetail-status">-</div>
                    </div>
                    <div class="detail-item">
                        <div class="detail-label">评级扣分</div>
                        <div class="detail-value" id="compDetail-ratingDeduction">-</div>
                    </div>
                    <div class="detail-item full-width">
                        <div class="detail-label">投诉描述</div>
                        <div class="detail-value description" id="compDetail-description">-</div>
                    </div>
                    <div class="detail-item full-width" id="compDetail-reviewContainer" style="display: none;">
                        <div class="detail-label">审批意见</div>
                        <div class="detail-value description" id="compDetail-reviewDescription">-</div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function () {
        // 确保 DOM 加载完成后执行
        var menuItems = document.querySelectorAll('.menu-item > a');
        menuItems.forEach(function (item) {
            item.addEventListener('click', function (e) {
                var parent = item.parentElement;
                document.querySelectorAll('.menu-item').forEach(function (el) {
                    if (el !== parent) el.classList.remove('active');
                });
                parent.classList.toggle('active');

                // 对于首页菜单项，不阻止默认行为，允许页面跳转
                if (!item.getAttribute('href').includes('employee_home.html')) {
                    e.preventDefault();
                }
            });
        });

        // 检查当前页面是否是首页，如果是则高亮首页菜单
        const currentPath = window.location.pathname;
        if (currentPath.includes('employee_home.html')) {
            document.querySelector('.menu-item:first-child').classList.add('active');
        }
        // 默认展开供应商管理菜单
        const providerMenuItem = document.querySelector('.menu-item:nth-child(5)');
        if (providerMenuItem) {
            providerMenuItem.classList.add('active');
        }
        // 设置当前页面对应的菜单项为选中状态
        const filename = currentPath.substring(currentPath.lastIndexOf('/') + 1);
        document.querySelectorAll('.submenu li a').forEach(link => {
            if (link.getAttribute('href') === filename) {
                link.classList.add('active');
            }
        });
        // 加载供应商数据
        loadProviders();
    });

    // 显示供应商申请准入模态框
    function showProviderApplicationForm() {
        const modal = new bootstrap.Modal(document.getElementById('providerApplicationModal'));
        modal.show();
        // 清空表单和验证提示
        document.getElementById('providerApplicationForm').reset();
        clearFormValidation();
    }

    // 在模态框显示时清除验证错误
    document.addEventListener('DOMContentLoaded', function() {
        const providerModal = document.getElementById('providerApplicationModal');
        providerModal.addEventListener('show.bs.modal', function() {
            document.getElementById('providerApplicationForm').reset();
            clearFormValidation();
        });
    });

    // 清除所有表单字段的错误提示
    function clearFormValidation() {
        // 移除所有错误提示
        document.querySelectorAll('.invalid-feedback').forEach(el => el.remove());
        document.querySelectorAll('.is-invalid').forEach(el => el.classList.remove('is-invalid'));
    }

    // 显示表单字段的错误提示
    function showFieldError(fieldId, errorMessage) {
        const field = document.getElementById(fieldId);
        field.classList.add('is-invalid');

        // 检查是否已存在错误提示，避免重复添加
        const existingFeedback = field.nextElementSibling;
        if (existingFeedback && existingFeedback.classList.contains('invalid-feedback')) {
            existingFeedback.textContent = errorMessage;
        } else {
            const errorDiv = document.createElement('div');
            errorDiv.className = 'invalid-feedback';
            errorDiv.textContent = errorMessage;
            field.insertAdjacentElement('afterend', errorDiv);
        }
    }

    // 验证表单
    function validateProviderForm() {
        clearFormValidation();
        let isValid = true;

        // 验证供应商名称
        const providerName = document.getElementById('providerName').value.trim();
        if (!providerName) {
            showFieldError('providerName', '请输入供应商名称');
            isValid = false;
        }

        // 验证厂址
        const factoryAddress = document.getElementById('factoryAddress').value.trim();
        if (!factoryAddress) {
            showFieldError('factoryAddress', '请输入厂址');
            isValid = false;
        }

        // 验证经理姓名
        const managerName = document.getElementById('managerName').value.trim();
        if (!managerName) {
            showFieldError('managerName', '请输入经理姓名');
            isValid = false;
        }

        // 验证经理电话
        const managerPhone = document.getElementById('managerPhone').value.trim();
        if (!managerPhone) {
            showFieldError('managerPhone', '请输入经理电话');
            isValid = false;
        } else if (!/^1[3-9]\d{9}$/.test(managerPhone)) {
            showFieldError('managerPhone', '请输入有效的11位手机号码');
            isValid = false;
        }

        // 验证企业类型
        const companyType = document.getElementById('companyType').value;
        if (!companyType) {
            showFieldError('companyType', '请选择企业类型');
            isValid = false;
        }

        // 验证注册资本
        const registeredCapital = document.getElementById('registeredCapital').value;
        if (!registeredCapital) {
            showFieldError('registeredCapital', '请输入注册资本');
            isValid = false;
        } else if (parseFloat(registeredCapital) <= 0) {
            showFieldError('registeredCapital', '注册资本必须大于0');
            isValid = false;
        }

        // 验证员工数量
        const employeeCount = document.getElementById('employeeCount').value;
        if (!employeeCount) {
            showFieldError('employeeCount', '请输入员工数量');
            isValid = false;
        } else if (parseInt(employeeCount) <= 0) {
            showFieldError('employeeCount', '员工数量必须大于0');
            isValid = false;
        }

        // 验证成立年份
        const establishedYear = document.getElementById('establishedYear').value;
        if (!establishedYear) {
            showFieldError('establishedYear', '请输入成立年份');
            isValid = false;
        } else {
            const year = parseInt(establishedYear);
            const currentYear = new Date().getFullYear();
            if (year < 1900 || year > currentYear) {
                showFieldError('establishedYear', `成立年份必须在1900至${currentYear}之间`);
                isValid = false;
            }
        }

        return isValid;
    }

    // 提交供应商申请
    async function submitProviderApplication() {
        // 首先验证表单
        if (!validateProviderForm()) {
            return; // 如果验证失败，停止提交
        }

        // 从localStorage获取申请人工号
        const userInfo = localStorage.getItem('userInfo');
        const user = JSON.parse(userInfo);
        const applicantJobNumber = user.jobNumber || '';

        const formData = {
            providerName: document.getElementById('providerName').value.trim(),
            factoryAddress: document.getElementById('factoryAddress').value.trim(),
            managerName: document.getElementById('managerName').value.trim(),
            managerPhone: document.getElementById('managerPhone').value.trim(),
            companyType: document.getElementById('companyType').value,
            registeredCapital: parseFloat(document.getElementById('registeredCapital').value),
            employeeCount: parseInt(document.getElementById('employeeCount').value),
            establishedYear: parseInt(document.getElementById('establishedYear').value),
            profile: document.getElementById('profile').value.trim(),
            applicantJobNumber: applicantJobNumber,
            isApproved: false,
            status: false
        };

        try {
            // 使用Axios发送请求，设置超时时间为3秒
            const response = await axios.post('http://localhost:8080/api/provider/application/submit', formData, {
                timeout: 3000, // 3秒超时
                headers: {
                    'Content-Type': 'application/json'
                }
            });

            // Axios自动解析JSON响应
            const result = response.data;
            alert(result.message || '供应商申请提交成功！');
            document.getElementById('providerApplicationForm').reset(); // 清空表单
            clearFormValidation(); // 清除验证提示
            document.getElementById('providerApplicationModal').querySelector('.btn-close').click(); // 关闭模态框
        } catch (error) {
            console.error('提交供应商申请时出错:', error);

            // 根据Axios错误类型提供不同的错误信息
            if (error.code === 'ECONNABORTED') {
                alert('网络请求超时，请检查您的网络连接或稍后重试');
            } else if (error.message && error.message.includes('Network Error')) {
                alert('网络连接错误，请检查您的网络连接是否正常');
            } else if (error.response) {
                // 服务器返回了错误状态码
                const errorMsg = error.response.data.message || `请求失败，状态码: ${error.response.status}`;
                alert(errorMsg);
            } else {
                alert('提交供应商申请时发生错误，请稍后重试');
            }
        }
    }

    async function loadProviders() {
        try {
            // 使用Axios发送请求，设置超时时间为10秒
            const response = await axios.get('http://localhost:8080/api/providers', {
                timeout: 10000 // 10秒超时
            });

            // Axios自动解析JSON响应
            const data = response.data;
            displayProviders(data);
        } catch (error) {
            console.error('加载供应商数据失败:', error);

            // 根据Axios错误类型提供不同的错误信息
            if (error.code === 'ECONNABORTED') {
                alert('网络请求超时，请检查您的网络连接或稍后重试');
            } else if (error.message && error.message.includes('Network Error')) {
                alert('网络连接错误，请检查您的网络连接是否正常');
            } else if (error.response) {
                // 服务器返回了错误状态码
                alert(`加载供应商数据失败，状态码: ${error.response.status}`);
            } else {
                alert('加载供应商数据失败，请确保后端服务正在运行');
            }
        }
    }

    function displayProviders(providers) {
        const tbody = document.getElementById('providerTableBody');
        tbody.innerHTML = '';

        // 添加数据验证，确保providers是数组
        if (!Array.isArray(providers)) {
            console.error('接收到的数据不是数组格式:', providers);
            tbody.innerHTML = '<tr><td colspan="10" class="text-center">无法加载数据，请检查后端服务</td></tr>';
            return;
        }

        if (providers.length === 0) {
            tbody.innerHTML = '<tr><td colspan="10" class="text-center">暂无供应商数据</td></tr>';
            return;
        }

        // 原有的遍历逻辑
        providers.forEach(provider => {
            const row = document.createElement('tr');
            row.innerHTML = `
                    <td>${provider.providerName}</td>
                    <td>${provider.factoryAddress || ''}</td>
                    <td>${provider.managerName || ''}</td>
                    <td>${provider.managerPhone || ''}</td>
                    <td>${provider.companyType || ''}</td>
                    <td>${provider.registeredCapital || 0}</td>
                    <td>${provider.employeeCount || 0}</td>
                    <td>${provider.establishedYear || ''}</td>
                    <td>${provider.providerRating || 0}</td>
                    <td>
                        <div class="action-buttons">
                            <button class="btn btn-sm btn-secondary" onclick="viewProviderDetail('${provider.providerName}')">详情</button>
                            <button class="btn btn-sm btn-secondary" onclick="complainProvider('${provider.providerName}')">投诉</button>
                        </div>
                    </td>
                `;
            tbody.appendChild(row);
        });
    }

    function searchProviders() {
        const searchParams = {
            providerName: document.getElementById('searchProviderName').value.toLowerCase(),
            companyType: document.getElementById('searchCompanyType').value,
            managerName: document.getElementById('searchManagerName').value.toLowerCase(),
            providerRating: document.getElementById('searchProviderRating').value
        };
        const tbody = document.getElementById('providerTableBody');
        const rows = tbody.getElementsByTagName('tr');
        for (let row of rows) {
            const cells = row.getElementsByTagName('td');
            const rowData = {
                providerName: cells[0].textContent.toLowerCase(),
                companyType: cells[4].textContent,
                managerName: cells[2].textContent.toLowerCase(),
                providerRating: cells[8].textContent
            };
            let visible = true;
            for (const [key, value] of Object.entries(searchParams)) {
                if (value && key === 'providerRating') {
                    if (rowData[key] != value) {
                        visible = false;
                        break;
                    }
                } else if (value && !rowData[key].includes(value)) {
                    visible = false;
                    break;
                }
            }
            row.style.display = visible ? '' : 'none';
        }
    }

    function resetSearch() {
        document.getElementById('searchProviderName').value = '';
        document.getElementById('searchCompanyType').value = '';
        document.getElementById('searchManagerName').value = '';
        document.getElementById('searchProviderRating').value = '';
        const tbody = document.getElementById('providerTableBody');
        const rows = tbody.getElementsByTagName('tr');
        for (let row of rows) {
            row.style.display = '';
        }
    }

    function addProvider() {
        window.location.href = 'provider_edit.html';
    }

    function editProvider(providerName) {
        window.location.href = `provider_edit.html?name=${encodeURIComponent(providerName)}`;
    }

    function viewProviderDetail(providerName) {
        getProviderByName(providerName).then(provider => {
            if (provider) {
                document.getElementById('detailProviderName').textContent = provider.providerName || '-';
                document.getElementById('detailFactoryAddress').textContent = provider.factoryAddress || '-';
                document.getElementById('detailManagerName').textContent = provider.managerName || '-';
                document.getElementById('detailManagerPhone').textContent = provider.managerPhone || '-';
                document.getElementById('detailCompanyType').textContent = provider.companyType || '-';
                document.getElementById('detailRegisteredCapital').textContent = provider.registeredCapital || '-';
                document.getElementById('detailEmployeeCount').textContent = provider.employeeCount || '-';
                document.getElementById('detailEstablishedYear').textContent = provider.establishedYear || '-';
                document.getElementById('detailProviderRating').textContent = provider.providerRating || '-';
                document.getElementById('detailProfile').textContent = provider.profile || '-';
                showProviderDetailModal();
            }
        });
    }

    // 显示iOS风格模态框
    function showProviderDetailModal() {
        const modal = document.getElementById('providerDetailModal');
        modal.classList.add('show');
        modal.onclick = function (e) {
            if (e.target === modal) {
                closeProviderDetailModal();
            }
        };
    }

    // 关闭iOS风格模态框
    function closeProviderDetailModal() {
        const modal = document.getElementById('providerDetailModal');
        modal.classList.remove('show');
    }

    // ESC键关闭模态框
    document.addEventListener('keydown', function (e) {
        if (e.key === 'Escape') {
            closeProviderDetailModal();
        }
    });

    async function getProviderByName(providerName) {
        try {
            const response = await axios.get(`http://localhost:8080/api/providers/${encodeURIComponent(providerName)}`, {
                timeout: 5000 // 5秒超时
            });
            return response.data; // Axios自动解析JSON响应
        } catch (error) {
            console.error('获取供应商详情失败:', error);
            return null;
        }
    }

    async function deleteProvider(providerName) {
        if (confirm('确定要删除这个供应商吗？')) {
            try {
                const response = await axios.delete(`http://localhost:8080/api/providers/${encodeURIComponent(providerName)}`, {
                    timeout: 5000 // 5秒超时
                });
                alert(response.data.message);
                loadProviders();
            } catch (error) {
                console.error('删除供应商时出错:', error);
                if (error.response && error.response.data) {
                    alert(error.response.data.message || '删除失败');
                } else {
                    alert('删除供应商时发生错误，请稍后重试');
                }
            }
        }
    }

    // 显示供应商投诉模态框
    async function complainProvider(providerName) {
        // 设置供应商名称
        document.getElementById('complaintProviderName').value = providerName;

        try {
            const response = await axios.get(`http://localhost:8080/api/materials/provider/${encodeURIComponent(providerName)}`);
            const materials = response.data;

            const materialSelect = document.getElementById('defectiveMaterial');
            materialSelect.innerHTML = '<option value="" selected disabled>请选择问题材料</option>';

            materials.forEach(material => {
                const option = document.createElement('option');
                option.value = material.materialNumber; // 使用 物料编号 字段作为 value
                option.textContent = `${material.name} (${material.specification})`; // 组合显示名称和规格
                materialSelect.appendChild(option);
            });

            // 显示模态框
            const modal = new bootstrap.Modal(document.getElementById('providerComplaintModal'));
            modal.show();

            // 清空表单和验证提示
            document.getElementById('complaintDescription').value = '';
            clearComplaintFormValidation();
        } catch (error) {
            console.error('获取供应商材料失败:', error);
            alert('获取供应商材料失败，请稍后重试');
        }
    }

    // 清除投诉表单的验证提示
    function clearComplaintFormValidation() {
        const form = document.getElementById('providerComplaintForm');
        form.querySelectorAll('.invalid-feedback').forEach(el => el.remove());
        form.querySelectorAll('.is-invalid').forEach(el => el.classList.remove('is-invalid'));
    }

    // 验证投诉表单
    function validateComplaintForm() {
        clearComplaintFormValidation();
        let isValid = true;

        // 验证问题材料
        const defectiveMaterial = document.getElementById('defectiveMaterial').value;
        if (!defectiveMaterial) {
            showFieldError('defectiveMaterial', '请选择问题材料');
            isValid = false;
        }

        // 验证投诉描述
        const description = document.getElementById('complaintDescription').value.trim();
        if (!description) {
            showFieldError('complaintDescription', '请输入投诉描述');
            isValid = false;
        }

        return isValid;
    }

    // 提交投诉
    async function submitComplaint() {
        if (!validateComplaintForm()) return;

        const userInfo = JSON.parse(localStorage.getItem('userInfo'));

        const complaintData = {
            providerName: document.getElementById('complaintProviderName').value,
            defectiveMaterial: document.getElementById('defectiveMaterial').value, // 这里已经是物料的编号
            description: document.getElementById('complaintDescription').value.trim(),
            complainantJobNumber: userInfo?.jobNumber || '',
            isApproved: false,
            status: false
        };

        try {
            const response = await axios.post(
                'http://localhost:8080/api/provider/complaints/submit',
                complaintData,
                {
                    timeout: 5000,
                    headers: { 'Content-Type': 'application/json' }
                }
            );

            alert(response.data.message || '投诉提交成功');

            const modal = bootstrap.Modal.getInstance(document.getElementById('providerComplaintModal'));
            modal.hide();
            document.getElementById('providerComplaintForm').reset();
            clearComplaintFormValidation();
        } catch (error) {
            console.error('提交投诉失败:', error);

            let errorMessage = '投诉提交失败，请稍后重试';

            if (error.response && error.response.data) {
                errorMessage = error.response.data.message || errorMessage;
            } else if (error.code === 'ECONNABORTED') {
                errorMessage = '网络请求超时，请检查网络连接';
            }

            alert(errorMessage);
        }
    }

    function logout() {
        // 添加确认提示
        if (confirm('确定要退出登录吗？')) {
            // 清除本地存储的登录信息
            localStorage.removeItem('userInfo');
            localStorage.removeItem('token');

            // 跳转到登录页面
            window.location.href = '../../../login.html';
        }
    }

    // 显示申请记录模态框
    async function showApplicationRecords() {
        try {
            const userInfo = JSON.parse(localStorage.getItem('userInfo'));
            if (!userInfo || !userInfo.jobNumber) {
                throw new Error('未找到用户信息');
            }

            const response = await axios.get('http://localhost:8080/api/provider/application/getApplications');
            const applications = response.data;
            
            // 过滤出当前用户的申请记录
            const userApplications = applications.filter(app => app.applicantJobNumber === userInfo.jobNumber);
            
            const tbody = document.getElementById('applicationRecordsBody');
            tbody.innerHTML = '';
            
            userApplications.forEach(app => {
                const row = document.createElement('tr');
                let statusText = '';
                let statusClass = '';
                
                if (!app.status) {
                    statusText = '待审核';
                    statusClass = 'text-warning';
                } else if (app.approved) {
                    statusText = '已批准';
                    statusClass = 'text-success';
                } else {
                    statusText = '已驳回';
                    statusClass = 'text-danger';
                }
                
                row.innerHTML = `
                    <td>${app.providerName}</td>
                    <td>${app.companyType}</td>
                    <td>${app.managerName}</td>
                    <td>${app.managerPhone}</td>
                    <td class="${statusClass}">${statusText}</td>
                `;

                // 添加点击事件
                row.addEventListener('click', () => showApplicationDetail(app, statusText, statusClass));
                tbody.appendChild(row);
            });
            
            const modal = new bootstrap.Modal(document.getElementById('applicationRecordsModal'));
            modal.show();
        } catch (error) {
            console.error('加载申请记录失败:', error);
            alert('加载申请记录失败，请稍后重试');
        }
    }

    // 显示投诉记录模态框
    async function showComplaintRecords() {
        try {
            const userInfo = JSON.parse(localStorage.getItem('userInfo'));
            if (!userInfo || !userInfo.jobNumber) {
                throw new Error('未找到用户信息');
            }

            const response = await axios.get('http://localhost:8080/api/provider/complaints/getComplaint');
            const complaints = response.data;
            
            // 过滤出当前用户的投诉记录
            const userComplaints = complaints.filter(complaint => complaint.complainantJobNumber === userInfo.jobNumber);
            
            const tbody = document.getElementById('complaintRecordsBody');
            tbody.innerHTML = '';
            
            userComplaints.forEach(complaint => {
                const row = document.createElement('tr');
                let statusText = '';
                let statusClass = '';
                
                if (!complaint.status) {
                    statusText = '待审核';
                    statusClass = 'text-warning';
                } else if (complaint.approved) {
                    statusText = '已批准';
                    statusClass = 'text-success';
                } else {
                    statusText = '已驳回';
                    statusClass = 'text-danger';
                }
                
                row.innerHTML = `
                    <td>${complaint.providerName}</td>
                    <td>${complaint.defectiveMaterial}</td>
                    <td class="description-cell">${complaint.description}</td>
                    <td class="${statusClass}">${statusText}</td>
                `;

                // 添加点击事件
                row.addEventListener('click', () => showComplaintDetail(complaint, statusText, statusClass));
                tbody.appendChild(row);
            });
            
            const modal = new bootstrap.Modal(document.getElementById('complaintRecordsModal'));
            modal.show();
        } catch (error) {
            console.error('加载投诉记录失败:', error);
            alert('加载投诉记录失败，请稍后重试');
        }
    }

    // 显示申请详情
    async function showApplicationDetail(application, statusText, statusClass) {
        try {
            // 隐藏申请记录模态框
            const recordsModal = bootstrap.Modal.getInstance(document.getElementById('applicationRecordsModal'));
            recordsModal.hide();

            // 填充详情
            document.getElementById('appDetail-providerName').textContent = application.providerName || '-';
            document.getElementById('appDetail-companyType').textContent = application.companyType || '-';
            document.getElementById('appDetail-managerName').textContent = application.managerName || '-';
            document.getElementById('appDetail-managerPhone').textContent = application.managerPhone || '-';
            document.getElementById('appDetail-registeredCapital').textContent = application.registeredCapital ? `${application.registeredCapital}万元` : '-';
            document.getElementById('appDetail-employeeCount').textContent = application.employeeCount || '-';
            document.getElementById('appDetail-establishedYear').textContent = application.establishedYear || '-';
            document.getElementById('appDetail-profile').textContent = application.profile || '-';
            
            const statusElement = document.getElementById('appDetail-status');
            statusElement.textContent = statusText;
            statusElement.className = `detail-value ${statusClass}`;

            // 如果已经审核，获取审核意见
            const reviewContainer = document.getElementById('appDetail-reviewContainer');
            if (application.status) {
                try {
                    // 获取审核意见
                    const response = await axios.get(`http://localhost:8080/api/provider/application/getReviewById/${application.applicationId}`);
                    const review = response.data;
                    if (review && review.description) {
                        document.getElementById('appDetail-reviewDescription').textContent = review.description;
                        reviewContainer.style.display = 'block';
                    } else {
                        reviewContainer.style.display = 'none';
                    }
                } catch (error) {
                    console.error('获取审核意见失败:', error);
                    reviewContainer.style.display = 'none';
                }
            } else {
                reviewContainer.style.display = 'none';
            }

            // 显示详情模态框
            const detailModal = new bootstrap.Modal(document.getElementById('applicationDetailModal'));
            detailModal.show();

            // 监听详情模态框关闭事件，重新显示记录列表
            document.getElementById('applicationDetailModal').addEventListener('hidden.bs.modal', function () {
                recordsModal.show();
            }, { once: true });
        } catch (error) {
            console.error('显示申请详情失败:', error);
            alert('显示申请详情失败，请稍后重试');
        }
    }

    // 显示投诉详情
    async function showComplaintDetail(complaint, statusText, statusClass) {
        try {
            // 隐藏投诉记录模态框
            const recordsModal = bootstrap.Modal.getInstance(document.getElementById('complaintRecordsModal'));
            recordsModal.hide();

            // 填充详情
            document.getElementById('compDetail-providerName').textContent = complaint.providerName || '-';
            document.getElementById('compDetail-defectiveMaterial').textContent = complaint.defectiveMaterial || '-';
            document.getElementById('compDetail-description').textContent = complaint.description || '-';
            
            const statusElement = document.getElementById('compDetail-status');
            statusElement.textContent = statusText;
            statusElement.className = `detail-value ${statusClass}`;

            // 如果已经审核，获取审核意见
            const reviewContainer = document.getElementById('compDetail-reviewContainer');
            if (complaint.status) {
                try {
                    // 获取审核意见
                    const response = await axios.get(`http://localhost:8080/api/provider/complaints/getReviewById/${complaint.complaintId}`);
                    const review = response.data;
                    if (review) {
                        document.getElementById('compDetail-reviewDescription').textContent = review.description || '-';
                        document.getElementById('compDetail-ratingDeduction').textContent = review.ratingDeduction ? `${review.ratingDeduction}分` : '-';
                        reviewContainer.style.display = 'block';
                    } else {
                        reviewContainer.style.display = 'none';
                    }
                } catch (error) {
                    console.error('获取审核意见失败:', error);
                    reviewContainer.style.display = 'none';
                }
            } else {
                reviewContainer.style.display = 'none';
            }

            // 显示详情模态框
            const detailModal = new bootstrap.Modal(document.getElementById('complaintDetailModal'));
            detailModal.show();

            // 监听详情模态框关闭事件，重新显示记录列表
            document.getElementById('complaintDetailModal').addEventListener('hidden.bs.modal', function () {
                recordsModal.show();
            }, { once: true });
        } catch (error) {
            console.error('显示投诉详情失败:', error);
            alert('显示投诉详情失败，请稍后重试');
        }
    }
</script>
</body>
</html>